<template>
  <el-form
    ref="customForm"
    :model="modelValue"
    label-suffix=":"
    :rules="rules"
    v-bind="$attrs"
  >
    <el-row :gutter="gutter">
      <template v-for="(item, index) in options" :key="index">
        <el-col v-if="!item.hide" :span="item.span">
          <el-form-item
            :label="item.label"
            :label-width="item.labelWidth"
            :prop="item.prop"
          >
            <!-- <el-input v-model="value" /> -->
            <component
              v-bind="{ ...item.attrs }"
              v-on="{ ...item.on }"
              :is="componentsTypes[item.tag!]"
              v-model="value[item.prop!]"
            >
              <template v-if="item.children">
                <component
                  v-for="(child, index1) in item.children"
                  :key="index1"
                  v-bind="child.attrs"
                  :label="child.label"
                  :value="child.value"
                  :is="componentsTypes[child.tag!]"
                />
              </template>
            </component>
          </el-form-item>
        </el-col>
      </template>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { componentsTypes } from "./map";
import { getCurrentInstance } from "vue";
// import { ElInput, ElSelect, ElOption } from "element-plus";
import { FormOptions } from "./type";
import type { FormItemRule } from "element-plus";
let props = withDefaults(
  defineProps<{
    modelValue: Record<string, unknown>;
    options: FormOptions[];
    labelSuffix?: string;
    gutter: number;
  }>(),
  { options: () => [], labelSuffix: "" }
);

let value = computed<Record<string, any>>({
  set(val) {
    console.log("设置值");
    return props.modelValue;
  },
  get() {
    return props.modelValue;
  },
});
let rules = computed<Record<string, FormItemRule[]>>(() => {
  let obj: Record<string, FormItemRule[]> = {};
  props.options.forEach((item) => {
    obj[item.prop as string] = item.rules as FormItemRule[];
  });
  return obj;
});
let customForm = ref();
let expose: { [key: string]: any } = {};
let instance = getCurrentInstance();

onMounted(() => {
  console.log("customForm", Object.entries(customForm.value));
  for (let [key, value] of Object.entries(customForm.value)) {
    // insexpose[key as string] = customForm.value[key];
    instance!.exposed![key] = value;
  }
});
console.log("expose", expose);
defineExpose({ ...instance?.exposed });
</script>

<style scoped></style>
